package com.leyou.search.web;

import com.leyou.search.dto.SearchParamDTO;
import com.leyou.search.entity.Goods;
import com.leyou.search.service.SearchService;
import com.leyou.starter.elastic.dto.PageInfo;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @author 虎哥
 */
@RestController
@RequestMapping("goods")
public class SearchController {

    private final SearchService searchService;

    public SearchController(SearchService searchService) {
        this.searchService = searchService;
    }

    @GetMapping("initialization")
    public ResponseEntity<String> init(){
        // 初始化索引库
        searchService.createIndexAndMapping();
        // 初始化数据
        searchService.loadData();
        // 返回成功
        return ResponseEntity.ok("初始化索引库成功！");
    }

    /**
     * 自动补全查询
     * @param keyPrefix 用户输入的关键字
     * @return 补全推荐的内容
     */
    @GetMapping("suggestion")
    public Mono<List<String>> getSuggestion(@RequestParam("key") String keyPrefix){
        return searchService.getSuggestion(keyPrefix);
    }

    /**
     * 搜索商品
     * @param param 查询参数
     * @return 返回的商品分页结果
     */
    @PostMapping("list")
    public Mono<PageInfo<Goods>> searchGoodsList(@RequestBody SearchParamDTO param){
        return searchService.search(param);
    }
}
